<?php

namespace App\Http\Resources;

use App\Support\ResourceCollection;

class GameRecords extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return $this->collection->map([$this, 'item'])->all();
    }
    
    /**
     * 格式化单个数据
     *
     * @param \App\Models\GameRecord $record
     * @return array
     */
    public function item($record)
    {
        $item = object_only($record, [
            'id',
            'operate_result',
            'ware_name',
            'ware_image',
        ]);
        
        $item['created_at'] = (string) $record->created_at;
        
        if ($record->relationLoaded('user')) {
            $user = $record->user;
            
            $item['user'] = [
                'id' => $user->id,
                'nickname' => $user->nickname,
                'gender' => $user->gender,
                'avatar' => image_url($user->avatar),
            ];
        }
        
        return $item;
    }
}
